package com.hthy.futures.ui.fragment;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hthy.futures.AppConfig;
import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.api.OrderCode;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.base.CommonAdapter;
import com.hthy.futures.base.CommonViewHolder;
import com.hthy.futures.bean.Goods;
import com.hthy.futures.bean.SaveQuotePush;
import com.hthy.futures.bean.TradeOderStr;
import com.hthy.futures.bean.ht.BProductPriceInfo;
import com.hthy.futures.bean.ht.BRealTimeData;
import com.hthy.futures.bean.ht.BRealTimeQuotePush;
import com.hthy.futures.inter.BillEvent;
import com.hthy.futures.inter.NewOrderNeedRefresh;
import com.hthy.futures.inter.PostNewOrderClickListener;
import com.hthy.futures.ui.GoodsListDialog;
import com.hthy.futures.ui.GoodsTypeListDialog;
import com.hthy.futures.ui.OrderBuyDialog;
import com.hthy.futures.ui.OrderGuaDialog;
import com.hthy.futures.ui.OrderSellDialog;
import com.hthy.futures.ui.activity.MainActivity;
import com.hthy.futures.utils.CacheManager;
import com.hthy.futures.utils.DialogUtil;
import com.hthy.futures.utils.ErrorUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.StringUtils;
import com.hthy.futures.view.EditTextWithDel;
import com.hthy.futures.view.NumberAddSubView;
import com.vilyever.socketclient.SocketClient;
import com.wordplat.ikvstockchart.entry.EntrySet;

import net.hthy.bean.Trade;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import static com.hthy.futures.utils.Contant.TRADE_BUY;
import static com.hthy.futures.utils.Contant.TRADE_BUY_LIMIT;
import static com.hthy.futures.utils.Contant.TRADE_BUY_STOP;
import static com.hthy.futures.utils.Contant.TRADE_DATATYPE_LIMIT;
import static com.hthy.futures.utils.Contant.TRADE_DATATYPE_MARKET;
import static com.hthy.futures.utils.Contant.TRADE_DIRECTION_BUY;
import static com.hthy.futures.utils.Contant.TRADE_DIRECTION_SELL;
import static com.hthy.futures.utils.Contant.TRADE_FLAG_NEW;
import static com.hthy.futures.utils.Contant.TRADE_NEW;
import static com.hthy.futures.utils.Contant.TRADE_OPER_ACCOUNT;
import static com.hthy.futures.utils.Contant.TRADE_SELL;
import static com.hthy.futures.utils.Contant.TRADE_SELL_LIMIT;
import static com.hthy.futures.utils.Contant.TRADE_SELL_STOP;

/**
 * 新订单
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/6
 */

// 这个应该是通过拿取行情数据来确定的“止损”“止盈”。
// 这里面应该是当新下完一个单子应该通知资金页面去重新请求单据请求 TODO

public class NewOrderFragment extends BaseFragment {
    @Bind(R.id.bt_post)
    Button mBtPost;
    @Bind(R.id.ll_resting_order)
    LinearLayout mLlRestingOrder;
    @Bind(R.id.ll_market_order)
    LinearLayout mLlMarketOrder;
    @Bind(R.id.et_num)
    EditTextWithDel mEtNum;
    @Bind(R.id.et_price)
    EditText mEtPrice;
    @Bind(R.id.stop_surplus2)
    EditText mEtStopSurplus;
    @Bind(R.id.et_stop_loss)
    EditText mEtStopLoss;
    @Bind(R.id.group)
    RadioGroup mGroup;
    @Bind(R.id.rb_buy)
    RadioButton mRadioBuy;
    @Bind(R.id.rb_sell)
    RadioButton mRadioSell;

    @Bind(R.id.ll_neworder)
    LinearLayout mLlNewOrder;
    @Bind(R.id.rg)
    RadioGroup mTypeGroup;
    @Bind(R.id.ll_bottom)
    LinearLayout mBottom;
    @Bind(R.id.tv_shi)
    RadioButton mTShi;

    @Bind(R.id.tv_gua)
    RadioButton mTGua;

    @Bind(R.id.tv_tip)
    TextView mTip;
    @Bind(R.id.tv_tip2)
    TextView mTip2;
    @Bind(R.id.tv_tip3)
    TextView mTip3;
    @Bind(R.id.llgua)
    LinearLayout mGua;
    @Bind(R.id.ll_value)
    LinearLayout mValue;

    @Bind(R.id.ll_market)
    LinearLayout mLlMarket;
    @Bind(R.id.ll_pending_order)
    LinearLayout mPendingOrder;

    @Bind(R.id.numaddSub)
    NumberAddSubView mNumberAddSubView;

    /*
    *   控制各个价格提示计算
    * */
    @Bind(R.id.tv_tip_tab1_yin)
    TextView mTvTipTab1_buy_Yin;
    @Bind(R.id.tv_tip_tab1_sun)
    TextView mTvTipTab1_buy_Sun;
    @Bind(R.id.ll_tab1_yin)
    LinearLayout mLlTab1Sell;
    @Bind(R.id.tv_tip_tab1_yin2)
    TextView mTvTipTab1_sell_Yin;
    @Bind(R.id.tv_tip_tab1_sun2)
    TextView mTvTipTab1_sell_Sun;
    @Bind(R.id.ll_tab1_sun)
    LinearLayout mLlTab1Buy;
    @Bind(R.id.tv_tip_tab2_yin)
    TextView mTvTipTab2Yin;
    @Bind(R.id.tv_tip_tab2_sun)
    TextView mTvTipTab2Sun;
    @Bind(R.id.ll_tab2)
    LinearLayout mLlTab2;
    @Bind(R.id.tv_tip2_guaprice)
    TextView mTip2_graprice;


    @Bind(R.id.ll_new_rule)
    LinearLayout mLlNewRule;    // 这个是新需求中的止盈止损的 linnerlayout
    @Bind(R.id.rg_newrule_sun)
    RadioGroup mRgNewRuleSuan;
    @Bind(R.id.rg_newrule)
    RadioGroup mRgnewRule;

    @Bind(R.id.bt_choose_goodstype)
    Button mGoodsType;
    private String mNum;
    private String mStopSurplus;
    private String mStopLoss;
    private boolean isFromPost = false;
    private List<String> mGoodList;
    @Bind(R.id.reference_margin)
    TextView mReferenceMargin;
    private boolean isMarketOrder = true;   // 市场价


    private String tradeDiration;
    private String tradeType;
    private String mCommitionPrice = "";
    private String mPendingChoose;
    private String mGoodsChoose;

    private String mTradeCode;
    private List<Goods> mGoodsList = new ArrayList<>();
    private TradeOderStr mOrderStr;
    private boolean isFromNewOrder;
    private OrderBuyDialog orderBuyDialog;
    private OrderSellDialog orderSellDialog;
    private int mSppinerIndex = 0;   // 默认选中第一个item
    private OrderGuaDialog orderGuaDialog;
    private double mOrder_s_spread;
    private double mOrder_y_spread;
    private double mGua_buystop;
    private double mGua_sell_limit;
    private double mGua_buylimit;
    private double mGua_stop_sell;

    /*k line*/
    Context mContxt;
    private Resources res;
    private SocketClient mSocketClient;
    private double mAccupidMoney;
    private double newAccupidMoney;
    private double mUiPrice;

    @Bind(R.id.scrollView)
    ScrollView mScrollView;
    @Bind(R.id.bt_choose_goods)
    Button mBtChooseGoods;
    private List<BRealTimeQuotePush> mBrealTimeQuotePush;
    private CommonAdapter<Goods> mChooseGoodCommonAdapter;
    private KLineFragment mKLineFragment;
    private double one_hundred_percent = 1;
    private double zs_percenValue = one_hundred_percent;  // 止盈的百分比
    private double zy_percenValue = one_hundred_percent;  // 止损的百分比
    private double mContractUnit;  // 合约单位
    @Bind(R.id.rb_percent_nothing)
    RadioButton mYPercent;
    @Bind(R.id.rb_percent_loss_nothing)
    RadioButton mSPercent;
    private double chooseContract;  // 选中的商品的合约单位
    //商品的买卖价格
    private double mBuyPrice;
    private double mSellPrice;
    private double postzs;
    private boolean isOtherStopLossValue = false;
    private CommonAdapter<String> mPendingAdapter;


    public void onEventMainThread(NewOrderNeedRefresh event) {
        if (event.isRefresh) {
            showViewVisable();
        }
    }

    public static NewOrderFragment getInstance() {
        NewOrderFragment newOrderFragment = new NewOrderFragment();
        return newOrderFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frg_new_order;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initWidget(final View root) {
        super.initWidget(root);

        // SoftHideKeyBoardUtil.addLayoutListener2(mLlNewOrder,mBtPost);

        mContxt = getActivity();
        res = mContxt.getResources();


        MainActivity.requestType = 0;

        mKLineFragment = new KLineFragment();
        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.ll_container, mKLineFragment);
        fragmentTransaction.show(mKLineFragment);
        fragmentTransaction.commit();

        if (AppContext.isMarket) {
            initTabTipView(8, 8, 8);
            mValue.setVisibility(View.GONE);   // 暂时性隐藏 为了配合新需求
            mLlNewRule.setVisibility(View.VISIBLE);
        } else {
            initTabTipView(0, 8, 8);
            mValue.setVisibility(View.VISIBLE);   // 暂时性隐藏 为了配合新需求
            mLlNewRule.setVisibility(View.GONE);
        }

        mLlMarket.setVisibility(View.VISIBLE);
        mPendingOrder.setVisibility(View.GONE);

        mTip2.setVisibility(View.GONE);
        mTip3.setVisibility(View.GONE);
        //showViewGone();
        mNumberAddSubView.setValue(1);
        mNumberAddSubView.setOnButtonClickListener(new NumberAddSubView.OnButtonClickListener() {
            @Override
            public void onButtonAddClick(View view, int value) {
                calurateGuaranteeMoney();
            }

            @Override
            public void onButtonSubClick(View view, int value) {
                calurateGuaranteeMoney();
            }
        });
        // 商品的spinner
        mEtPrice.addTextChangedListener(watcher);

        // 挂单类型的spinner
        // mPendingChooseType = (Spinner) root.findViewById(R.id.editSpinner2);
        mGoodList = new ArrayList<>();
        List<String> pendingList = new ArrayList<>();
        pendingList.add(getActivity().getResources().getString(R.string.pending_type_buylimit));
        pendingList.add(getActivity().getResources().getString(R.string.pending_type_selllimit));
        pendingList.add(getActivity().getResources().getString(R.string.pending_type_buystop));
        pendingList.add(getActivity().getResources().getString(R.string.pending_type_sellstop));

        mPendingAdapter = new CommonAdapter<String>(getActivity(), R.layout.spin_view) {
            @Override
            public void convert(CommonViewHolder vh, String item) {
                vh.setText(R.id.spin_value, item);

            }
        };
        mPendingAdapter.addItem(pendingList);
        mPendingChoose = pendingList.get(0);
        mGoodsType.setText(pendingList.get(0));


        // 选择市价单，挂单
        mTShi.setChecked(true);
        setMarketView();
        mTip2_graprice.setVisibility(View.GONE);


        mTypeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tv_shi:
                        setMarketView();
                        if (tradeDiration.equals(TRADE_DIRECTION_BUY)) {
                            if (AppContext.isMarket) {
                                initTabTipView(8, 8, 8);  // ----
                            } else {
                                initTabTipView(0, 8, 8);
                            }
                        } else {
                            if (AppContext.isMarket) {
                                initTabTipView(8, 8, 8);
                            } else {
                                initTabTipView(8, 0, 8);
                            }
                        }
                        mTip2_graprice.setVisibility(View.GONE);

                        if (AppContext.isMarket) {
                            mValue.setVisibility(View.GONE);   // 暂时性隐藏 为了配合新需求
                            mLlNewRule.setVisibility(View.VISIBLE);
                        } else {
                            mValue.setVisibility(View.VISIBLE);   // 暂时性隐藏 为了配合新需求
                            mLlNewRule.setVisibility(View.GONE);
                        }


                        if (zs_percenValue == one_hundred_percent) {
                            isOtherStopLossValue = true;
                        }
                        break;
                    case R.id.tv_gua:
                        setGuaView();

                        if (AppContext.isMarket) {
                            initTabTipView(8, 8, 8);  // ----
                        } else {
                            initTabTipView(8, 8, 0);
                        }
                        mTip2_graprice.setVisibility(View.VISIBLE);

                        // 现在限价单中的止盈价和止损价不显示
                        mLlTab2.setVisibility(View.GONE);

                        mValue.setVisibility(View.GONE);
                        mLlNewRule.setVisibility(View.GONE);

                        //getHistoryCachData();
                        isOtherStopLossValue = false;
                        break;
                }
            }
        });
        mRadioBuy.setChecked(true);
        setBuyseletIndex();
        mGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_buy:
                        setBuyseletIndex();

                        // 在这里计算最佳的止盈价格和止损价格
                        // 拿到行情数据中的价格，然后再结合 商品数据中的点差关系就可以拿到了
                        mBtPost.setBackground(getResources().getDrawable(R.drawable.btn_common_blue_style));
                        if (AppContext.isMarket) {
                            initTabTipView(8, 8, 8);
                        } else {
                            initTabTipView(0, 8, 8);
                        }
                        break;
                    case R.id.rb_sell:
                        tradeDiration = TRADE_DIRECTION_SELL;
                        tradeType = TRADE_SELL;

                        mBtPost.setBackground(getResources().getDrawable(R.drawable.btn_common_blue_style));
                        if (AppContext.isMarket) {
                            initTabTipView(8, 8, 8);
                        } else {
                            initTabTipView(8, 0, 8);
                        }
                        break;
                }
                sellbuyPercent();
            }
        });

        // 止盈选择
        mYPercent.setChecked(true);
        mRgnewRule.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                isOtherStopLossValue = true;
                switch (checkedId) {
                    case R.id.rb_percent_nothing:
                        zy_percenValue = one_hundred_percent;
                        break;
                    case R.id.rb_percent_20:
                        zy_percenValue = 0.2;
                        break;
                    case R.id.rb_percent_40:
                        zy_percenValue = 0.4;
                        break;
                    case R.id.rb_percent_60:
                        zy_percenValue = 0.6;
                        break;
                }
                sellbuyPercent();
            }
        });
        // 止损选择
        mSPercent.setChecked(true);
        mRgNewRuleSuan.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_percent_loss_nothing) {
                    isOtherStopLossValue = true;
                } else {
                    isOtherStopLossValue = false;
                }
                switch (checkedId) {
                    case R.id.rb_percent_loss_nothing:
                        zs_percenValue = one_hundred_percent;
                        break;
                    case R.id.rb_percent_loss_20:
                        zs_percenValue = 0.2;
                        break;
                    case R.id.rb_percent_loss_40:
                        zs_percenValue = 0.4;
                        break;
                    case R.id.rb_percent_loss_60:
                        zs_percenValue = 0.6;
                        break;
                }
                sellbuyPercent();
            }
        });

        // 先获取商品种类
        //String searchCode = ST_TradeApi.searchGoods("2015");
        byte[] baseStr2 = ST_TradeApi.searchGoods("2015");
        socketClient.sendData(baseStr2);
        isFromNewOrder = true;
    }

    /**
     * 控制各个面板的显示  0代表显示，8代表隐藏 flag 0代表市价单，1代表挂单
     *
     * @param visible_buy
     * @param visible_sell
     * @param visible_tab2
     */
    private void initTabTipView(int visible_buy, int visible_sell, int visible_tab2) {
        mLlTab1Buy.setVisibility(visible_buy);
        mLlTab1Sell.setVisibility(visible_sell);
        mLlTab2.setVisibility(visible_tab2);
    }


    /**
     * 默认选择买的选项
     */
    private void setBuyseletIndex() {
        tradeDiration = TRADE_DIRECTION_BUY;
        tradeType = TRADE_BUY;
        //mBtPost.setBackground(getResources().getDrawable(R.drawable.btn_common_red_style));
    }

    /**
     * 清空止损价等信息
     */
    private void clearEdit() {
        mEtStopSurplus.setText("");
        mEtStopLoss.setText("");
    }


    /**
     * //从orderfragment把数据传进来，不让会出现一种现象（主要市针对在tablayout+viewpager下的fragment产生的一种错误）
     * 给spinner 赋予数据
     *
     * @param
     */
    public void setListOrder(List<Goods> goodsData) {
        mChooseGoodCommonAdapter = new CommonAdapter<Goods>(getActivity(), R.layout.spin_view) {
            @Override
            public void convert(CommonViewHolder vh, Goods item) {
                vh.setText(R.id.spin_value, item.getSs_product_name());
            }
        };
        if (mChooseGoodCommonAdapter.getDatas().size() > 0) {
            mChooseGoodCommonAdapter.clear();
        }
        mChooseGoodCommonAdapter.addItem(goodsData);

        mBtChooseGoods.setText(goodsData.get(0).getSs_product_name());


        // 把集合拿过来
        if (mGoodList != null) {
            Goods selectedItem = mGoodsList.get(mSppinerIndex);
            showSelectIndexItem(selectedItem);
        }

    }


    @OnClick({R.id.bt_choose_goods, R.id.bt_post, R.id.btn_hold_sub, R.id.btn_hold_add, R.id.bt_choose_goodstype})
    public void onClick(View view) {
        mCommitionPrice = mEtPrice.getText().toString().trim();  // 委托价格
        double comprice = 0;
        if (mCommitionPrice != null && !"".equals(mCommitionPrice)) {
            comprice = StringUtils.toDouble(mCommitionPrice);
        }
        switch (view.getId()) {
            case R.id.bt_choose_goods:
                GoodsListDialog goodsListDialog = new GoodsListDialog(getActivity());
                goodsListDialog.setCancelable(false);
                goodsListDialog.setCanceledOnTouchOutside(true);
                goodsListDialog.setOnGoodsItemSelectedListener(new GoodsListDialog.OnGoodsItemSelectedListener() {
                    @Override
                    public void select(Goods selectedItem) {
                        showSelectIndexItem(selectedItem);
                    }
                });
                goodsListDialog.setGoodsAdapter(mChooseGoodCommonAdapter);
                goodsListDialog.show();
                break;
            case R.id.btn_hold_sub:
                if (comprice > 1) {
                    comprice--;
                    mEtPrice.setText(comprice + "");
                } else {
                    showToast("不能再减了");
                }
                break;
            case R.id.btn_hold_add:
                comprice++;
                mEtPrice.setText(comprice + "");
                break;
            case R.id.bt_choose_goodstype:
                GoodsTypeListDialog goodsTypeListDialog = new GoodsTypeListDialog(getActivity());
                goodsTypeListDialog.setCancelable(false);
                goodsTypeListDialog.setCanceledOnTouchOutside(true);
                goodsTypeListDialog.setOnGoodsItemSelectedListener(new GoodsTypeListDialog.OnGoodsItemSelectedListener() {
                    @Override
                    public void select(String seletStr) {
                        mPendingChoose = seletStr;
                        mGoodsType.setText(mPendingChoose);
                        getHistoryCachData();
                    }
                });
                goodsTypeListDialog.setGoodsTypeAdapter(mPendingAdapter);
                goodsTypeListDialog.show();
                break;
            case R.id.bt_post:

                if (!checkValide()) {
                    return;
                }
                // 提交订单的信息
                mOrderStr = getTradeOrderStr();

                DialogUtil.dimissDialog();

                if (isMarketOrder) {
                    if (tradeType == TRADE_BUY) {
                        // 应该是在弹出对话框
                        if (orderBuyDialog == null) {
                            orderBuyDialog = new OrderBuyDialog(getActivity());
                        }
                        orderBuyDialog.setCancelable(false);
                        orderBuyDialog.setCanceledOnTouchOutside(true);
                        orderBuyDialog.setIsOtherStopLossValue(isOtherStopLossValue);
                        orderBuyDialog.setOrderData(mOrderStr);
                        orderBuyDialog.setPostNewOrderClickListner(new PostNewOrderClickListener() {
                            @Override
                            public void post() {
                                postContent();
                            }
                        });
                        orderBuyDialog.show();
                    } else if (tradeType == TRADE_SELL) {
                        // 应该是在弹出对话框
                        if (orderSellDialog == null) {
                            orderSellDialog = new OrderSellDialog(getActivity());
                        }
                        orderSellDialog.setCancelable(false);
                        orderSellDialog.setCanceledOnTouchOutside(true);
                        orderSellDialog.setIsOtherStopLossValue(isOtherStopLossValue);
                        orderSellDialog.setOrderData(mOrderStr);

                        orderSellDialog.setPostNewOrderClickListner(new PostNewOrderClickListener() {
                            @Override
                            public void post() {
                                postContent();
                            }
                        });
                        orderSellDialog.show();
                    }
                } else {
                    if (orderGuaDialog == null) {
                        orderGuaDialog = new OrderGuaDialog(getActivity());
                    }
                    orderGuaDialog.setCancelable(false);
                    orderGuaDialog.setCanceledOnTouchOutside(true);
                    orderGuaDialog.setOrderData(mOrderStr);
                    orderGuaDialog.setPostNewOrderClickListner(new PostNewOrderClickListener() {
                        @Override
                        public void post() {
                            postContent();
                        }
                    });
                    orderGuaDialog.show();
                }
                break;
        }
    }

    /**
     * 提交订单内容的操作
     */
    private void postContent() {
        byte[] baseStr2 = ST_TradeApi.trade(isMarketOrder, OrderCode.O_1011, mOrderStr);
        socketClient.sendData(baseStr2);
        isFromPost = true;
    }

    /**
     * 选择挂单操作
     */
    private void setGuaView() {
        mLlMarket.setVisibility(View.GONE);
        mPendingOrder.setVisibility(View.VISIBLE);
        mGua.setVisibility(View.VISIBLE);

        mTip.setVisibility(View.GONE);
        mTip2.setVisibility(View.VISIBLE);
        mTip3.setVisibility(View.VISIBLE);
        //mValue.setVisibility(View.GONE);

        isMarketOrder = false;

        mTShi.setTextColor(Color.GRAY);

        mTGua.setTextColor(getResources().getColor(R.color.colorPrimary));
    }

    /**
     * 选择市价单操作
     */
    private void setMarketView() {
        mLlMarket.setVisibility(View.VISIBLE);
        mPendingOrder.setVisibility(View.GONE);
        mGua.setVisibility(View.GONE);

        mTip.setVisibility(View.VISIBLE);
        mTip2.setVisibility(View.GONE);
        mTip3.setVisibility(View.GONE);
        //mValue.setVisibility(View.VISIBLE);

        isMarketOrder = true;

        mTShi.setTextColor(getResources().getColor(R.color.colorPrimary));

        mTGua.setTextColor(Color.GRAY);
    }

    /**
     * 返回相关参数
     *
     * @return
     */
    private TradeOderStr getTradeOrderStr() {
        TradeOderStr tradeOderStr = new TradeOderStr();
        tradeOderStr.currentPrice = mUiPrice + "";

        tradeOderStr.tradeCode = mTradeCode;
        tradeOderStr.tradeBuyCount = mNum;
        tradeOderStr.tradeFlag = TRADE_FLAG_NEW;
        tradeOderStr.trade_operation_type = TRADE_OPER_ACCOUNT;

        tradeOderStr.trade_dicount_price = mStopSurplus;  // 止盈价
        // 在这里面判断如果有止损价的 “无”值  ，有些选他
        if (isOtherStopLossValue) {
            tradeOderStr.trade_stop_price = postzs + "";// 止损价
        } else {
            tradeOderStr.trade_stop_price = mStopLoss;// 止损价
        }
        //tradeOderStr.trade_stop_price = mStopLoss;// 止损价
        // 如果选市价单tab
        if (isMarketOrder) {
            tradeOderStr.tradeOC = TRADE_NEW;
            tradeOderStr.trade_data_type = TRADE_DATATYPE_MARKET;

            tradeOderStr.trade_direction = tradeDiration;// 买卖方向    s代表卖 b买
            tradeOderStr.trade_type = tradeType;  // 挂单类型  要一一对应
        } else {
            // 如果选择挂单tab
            tradeOderStr.tradeFlag = TRADE_FLAG_NEW;
            tradeOderStr.tradeOC = TRADE_NEW;
            tradeOderStr.trade_data_type = TRADE_DATATYPE_LIMIT;
            tradeOderStr.trade_commision_price = mCommitionPrice;  // 委托价格

            //交易类型   ‘1’- buy ,‘2’ - sell ,‘3’ - buy limit(限价买入） ,‘4’ - buy stop（止损买入） ,‘5’ - sell limit（限价卖出） ,‘6’ - sell stop（止损卖出）
            if (mPendingChoose.equals(getString(R.string.pending_type_buylimit))) {
                tradeOderStr.trade_type = TRADE_BUY_LIMIT;  // 挂单类型  要一一对应
                tradeOderStr.trade_direction = TRADE_DIRECTION_BUY;
            } else if (mPendingChoose.equals(getString(R.string.pending_type_selllimit))) {
                tradeOderStr.trade_type = TRADE_SELL_LIMIT;  // 挂单类型  要一一对应
                tradeOderStr.trade_direction = TRADE_DIRECTION_SELL;
            } else if (mPendingChoose.equals(getString(R.string.pending_type_buystop))) {
                tradeOderStr.trade_type = TRADE_BUY_STOP;  // 挂单类型  要一一对应
                tradeOderStr.trade_direction = TRADE_DIRECTION_BUY;
            } else if (mPendingChoose.equals(getString(R.string.pending_type_sellstop))) {
                tradeOderStr.trade_type = TRADE_SELL_STOP;  // 挂单类型  要一一对应
                tradeOderStr.trade_direction = TRADE_DIRECTION_SELL;
            }
        }
        return tradeOderStr;
    }

    /**
     * 检验合法性
     *
     * @return
     */
    private boolean checkValide() {
        // mGoodsChoose = this.goodsChoose // 商品 名字
        //mNum = mEtNum.getText().toString().trim(); // 手数

        mNum = mNumberAddSubView.getValue() + "";


        mCommitionPrice = mEtPrice.getText().toString().trim();  // 委托价格

        // 真是奇怪为啥获取不了值
        mStopSurplus = mEtStopSurplus.getText().toString().trim(); // 止盈价
        mStopLoss = mEtStopLoss.getText().toString().trim();   // 止损价
        // 挂单类型
        // mPendingChoose = mPendingChooseType.getEditString().toString().trim();
        if (StringUtils.isEmpty(mGoodsChoose)) {
            showToast(R.string.choose_goods);
            return false;
        }
        if (StringUtils.isEmpty(mNum)) {
            showToast(R.string.inputnum);
            return false;
        }

        if (isMarketOrder) {
            if (StringUtils.isEmpty(tradeDiration)) {
                showToast(R.string.choose_tradediration);
                return false;
            }
        } else {
            if (StringUtils.isEmpty(mPendingChoose)) {
                showToast(R.string.choose_pending);
                return false;
            }
            if (StringUtils.isEmpty(mCommitionPrice)) {
                showToast(R.string.commition_price);
                return false;
            }
        }
        return true;

    }

    @Override
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {
        super.onResponse(client, responMes, subBytes);
        LogUtils.e(responMes);

        if (isFromNewOrder && responMes.indexOf("2016") != -1) {
            if (mGoodsList != null && mGoodsList.size() > 0) {
                mGoodsList.clear();
            }
            try {
                Trade.QueryProductsResponseMsg queryProductsResponseMsg = Trade.QueryProductsResponseMsg.parseFrom(subBytes);
                List<Trade.UserProductsInfo> userProductsInfoList = queryProductsResponseMsg.getUserProductsInfoList();
                for (Trade.UserProductsInfo productsInfo : userProductsInfoList) {
                    Goods goods = new Goods();
                    goods.setSs_product_code(productsInfo.getSsProductCode());
                    goods.setSs_product_name(productsInfo.getSsProductName());
                    goods.setUi_buy_pips(productsInfo.getUiBuyPips() + "");
                    goods.setUi_sell_pips(productsInfo.getUiSellPips() + "");
                    goods.setUi_sl_pips(productsInfo.getUiSlPips() + "");
                    goods.setUi_tp_pips(productsInfo.getUiTpPips() + "");
                    goods.setDb_contract_size(productsInfo.getDbContractSize() + "");
                    goods.setDb_origin_margin(productsInfo.getDbOriginMargin() + "");
                    int uiMarginType = productsInfo.getUiMarginType();  // 因为他输出的是ascii值
                    goods.setUi_margin_type(49 == uiMarginType ? "1" : "2");
                    mGoodsList.add(goods);
                }

                setListOrder(mGoodsList);
                // getHistoryCachData();
                calurateGuaranteeMoney();

            } catch (Exception e) {
                e.printStackTrace();
            }
            isFromNewOrder = false;
        }
        if (isFromPost && responMes.indexOf("1012") != -1) {
            try {
                Trade.MakeOrderResponseMsg makeOrderResponseMsg = Trade.MakeOrderResponseMsg.parseFrom(subBytes);
                int iErrorCode = makeOrderResponseMsg.getResponseMsg().getIErrorCode();
                if (0 == iErrorCode) {
                    // 需要通知billfragment刷新下
                    EventBus.getDefault().post(new BillEvent(true));
                    DialogUtil.dimissDialog();
                    showToast(R.string.commit);
                    // 跳到单据页面中
                    ((MainActivity) getActivity()).set2Fragment2(1);
                } else {
                    ErrorUtils.sendErrorMes(getActivity(), iErrorCode + "");
                }
                isFromPost = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (mBrealTimeQuotePush == null) {
            showViewVisable();
            // getHistoryCachData();
        }
    }

    /**
     * 读历史数据
     */
    private void getHistoryCachData() {
        SaveQuotePush saveQuotePush = (SaveQuotePush) CacheManager.readObject(getActivity(), AppConfig.OFFETSHEET);
        // 得到报价表的缓存
        if (saveQuotePush != null) {
            List<BRealTimeData> getHistoryOFfersheets = saveQuotePush.mMyRelTimeDatas;
            if (saveQuotePush != null) {
                LogUtils.e("cache", "save" + getHistoryOFfersheets.size() + "");
            }
            setHistoryOfferSheests(getHistoryOFfersheets);
        }
    }

    /**
     * 计算参考保证金
     */
    private void calurateGuaranteeMoney() {
        mReferenceMargin.setText("计算中……");
        for (Goods goods : mGoodsList) {
            // 如果是选中的的那个商品
            if (mTradeCode != null && mTradeCode.equals(goods.getSs_product_code())) {

                Double initGuaranteeMoney = StringUtils.toDouble(goods.getDb_origin_margin()); // 初始保障金
                // 判断是保证金类型（包括比例与固定两种）
                String moneyHoldType = goods.getUi_margin_type();
                mContractUnit = StringUtils.toDouble(goods.getDb_contract_size());  // 合约单位
                int commitUnit = mNumberAddSubView.getValue();
                if (moneyHoldType.equals("1")) {  // 比例
                    // 占用保证金 = 商品信息->初始保证金 * 行情价 * 合约数量 * 单据数量
                    mAccupidMoney = initGuaranteeMoney * mUiPrice * mContractUnit * commitUnit;
                } else if (moneyHoldType.equals("2")) {
                    // 占用保证金 = 商品信息->初始保证金 * 单据数量
                    mAccupidMoney = initGuaranteeMoney * commitUnit;
                }
                mReferenceMargin.setText(StringUtils.double_df.format(mAccupidMoney));
                LogUtils.e("money", "mAccupidMoney" + mAccupidMoney + "mUiPrice" + mUiPrice);
                LogUtils.e("money", "initGuaranteeMoney" + initGuaranteeMoney + "mContractUnit" + mContractUnit);
                break;
            }
        }
        // sellbuyPercent();
    }


    /**
     * 通过报价表计算相应的合理的止损价等信息
     */
    public void setHistoryOfferSheests(List<BRealTimeData> getHistoryOFfersheets) {
        // 重新拼属于自己的bean
        for (Goods goods : mGoodsList) {
            for (BRealTimeData timePush : getHistoryOFfersheets) {
                BProductPriceInfo product_price_info = timePush.product_price_info;
                if ((product_price_info.ss_product_code).equals(goods.getSs_product_code())) {
                    goods.uiPrice = timePush.ui_last_price + "";
                    if (calculation(goods)) return;
                }
            }
        }
        showViewVisable();
    }

    /**
     * 计算过程处理
     *
     * @param goods
     * @return
     */
    private boolean calculation(Goods goods) {
        if (mTradeCode != null && mTradeCode.equals(goods.getSs_product_code())) {

            mUiPrice = Double.parseDouble(goods.uiPrice);

            calurateGuaranteeMoney();
            // 如果考虑到有新的韩起止

            double quote_buy_spread = Double.parseDouble(goods.getUi_buy_pips()); //8077 报价买价点差   比如10
            double quote_sell_spread = Double.parseDouble(goods.getUi_sell_pips()); // 8078 报价卖价点差

            mBuyPrice = mUiPrice + quote_buy_spread;  // 商品的买卖价格 之所以搞成全局变量是为了 计算止盈止损百分比
            mSellPrice = mUiPrice + quote_sell_spread;

            double oldBuyPrice = goods.oldBuyPrice;
            double oldSellPrice = goods.oldSellPrice;
            // 增加颜色的区分
            if (goods.oldBuyPrice != -1) {
                if (mBuyPrice > oldBuyPrice) {
                    // red
                    mRadioBuy.setTextColor(Color.RED);
                } else if (mBuyPrice == oldBuyPrice) {

                } else {
                    // blue
                    mRadioBuy.setTextColor(getResources().getColor(R.color.fund_float));
                }
            }
            if (goods.oldSellPrice != -1) {
                if (mSellPrice > oldSellPrice) {
                    // red
                    mRadioSell.setTextColor(Color.RED);
                } else if (mSellPrice == oldSellPrice) {

                } else {
                    // blue
                    mRadioSell.setTextColor(getResources().getColor(R.color.fund_float));
                }
            }
            goods.oldBuyPrice = mBuyPrice;
            goods.oldSellPrice = mSellPrice;

            // 用SpannableString打造绚丽多彩的文本显示效果
            String spanBuy = getString(R.string.buy) + " " + StringUtils.double_df.format(mBuyPrice);
            String spanSell = getString(R.string.sell) + " " + StringUtils.double_df.format(mSellPrice);
            SpannableString spannableBuyString = new SpannableString(spanBuy);
            SpannableString spannableSellString = new SpannableString(spanSell);
            setSpanColor(spannableBuyString);
            setSpanColor(spannableSellString);

            mRadioBuy.setText(spannableBuyString);
            mRadioSell.setText(spannableSellString);

            // 8129 止损下单点差  比如30
            mOrder_s_spread = Double.parseDouble(goods.getUi_sl_pips());
            // 8130 止盈下单点差
            mOrder_y_spread = Double.parseDouble(goods.getUi_tp_pips());


        /*市场价
         卖   止损价>= 行情价+30（点差）          止盈价<=行情价-30
         买   止损价>= 行情价-30（点差）          止盈价<=行情价+30
         */
            String buy_y = StringUtils.double_df.format(mBuyPrice + mOrder_s_spread);
            String buy_s = StringUtils.double_df.format(mSellPrice - mOrder_y_spread);

            String sell_y = StringUtils.double_df.format(mBuyPrice + mOrder_y_spread);
            String sell_s = StringUtils.double_df.format(mSellPrice - mOrder_s_spread);

            // EDIT　TODO
            // sellbuyPercent();


            // if (isMarketOrder) {
            mTip.setText("【买】止盈>=" + buy_y +
                    "止损<=" + buy_s + "\n" + "【卖】止盈<=" + sell_s +
                    "止损>=" + sell_y);
            mTvTipTab1_sell_Yin.setText("止盈>=" + buy_y);
            mTvTipTab1_sell_Sun.setText("止损<=" + buy_s);

            mTvTipTab1_buy_Yin.setText("止盈<=" + sell_s);
            mTvTipTab1_buy_Sun.setText("止损>=" + sell_y);


            //   } else {

            // 挂价单必须远离市价至少50点差
            // 挂单下的相关信息
        /*  限价买入  价位：<=行情价-50   止损 <=
            限价卖出   价位：<=行情价-50
            止损买入 价位：>=行情价+50
            止损卖出  价位：>=行情价+50
          */

            mGua_buystop = mBuyPrice + 50;
            mGua_sell_limit = mBuyPrice + 50;
            mGua_buylimit = mSellPrice - 50;
            mGua_stop_sell = mSellPrice - 50;
            if (mPendingChoose == null) {
                return true;
            }
            if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_buylimit))) {
                mTip2.setText("价位<=" + mGua_buylimit);
                mTip2_graprice.setText("价位<=" + mGua_buylimit);
            } else if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_selllimit))) {
                mTip2.setText("价位>=" + mGua_sell_limit);
                mTip2_graprice.setText("价位>=" + mGua_sell_limit);
            } else if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_buystop))) {
                mTip2.setText("价位>=" + mGua_buystop);
                mTip2_graprice.setText("价位>=" + mGua_buystop);
            } else if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_sellstop))) {
                mTip2.setText("价位<=" + mGua_stop_sell);
                mTip2_graprice.setText("价位<=" + mGua_stop_sell);
            }
            // 挂单的止盈止损如何计算 ( 跟前面不一致的，它是基于用户的填入的价位再和点差做相加减的）
            // String holdPrice = mEtPrice.getText().toString().trim();  // 挂单价格

            //  }
            //LogUtils.e("我选择" + mTradeCode + mRadioBuy.getText() + mRadioSell.getText() + "buychaValue" + quote_buy_spread + "sellchaValue" + quote_sell_spread + "order_s_spread" + order_s_spread);
        }
        return false;
    }

    private void setSpanColor(SpannableString spannableString) {
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#333333"));
        spannableString.setSpan(colorSpan, 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    /**
     * // 止盈止损百分比计算过程
     */
    private void sellbuyPercent() {
        // 止盈止损百分比计算过程           （在单据那边如果止损百分比>95%，也是不显示的）
        // 买 ：  止损价 = 当前价-（（保证金*止损百分比）/ 合约单位） ， 止盈价 = 当前价 +（（保证金*止盈百分比）/ 合约单位）
        // 卖的话：止损价 = 当前价+（（保证金*止损百分比）/ 合约单位）   止盈价 = 当前价 -（（保证金*止盈百分比）/ 合约单位）
        double referenceMarginPrice = StringUtils.toDouble(mReferenceMargin.getText().toString());

        if (zs_percenValue == one_hundred_percent) {
            mEtStopLoss.setText("");  // 止损价赋值

            // 如果是 止损价的话，即使是选择无 ，也要把值计算进来，传给服务器
            double zsdistance = (referenceMarginPrice * zs_percenValue) / chooseContract;
            if (!isOtherStopLossValue) {
                return;
            }
            if (tradeDiration == TRADE_DIRECTION_BUY) {
                //  如果是买方向
                double buy_zs = mBuyPrice - zsdistance;
                postzs = buy_zs;  // 止损价赋值

            } else if (tradeDiration == TRADE_DIRECTION_SELL) {
                //  如果是卖方向
                double sell_zs = mSellPrice + zsdistance;
                postzs = sell_zs;  // 止损价赋值
            }
        } else {
            double zsdistance = (referenceMarginPrice * zs_percenValue) / chooseContract;
            if (tradeDiration == TRADE_DIRECTION_BUY) {
                //  如果是买方向
                double buy_zs = mBuyPrice - zsdistance;
                mEtStopLoss.setText(buy_zs + "");  // 止损价赋值
            } else if (tradeDiration == TRADE_DIRECTION_SELL) {
                //  如果是卖方向
                double sell_zs = mSellPrice + zsdistance;
                mEtStopLoss.setText(sell_zs + "");  // 止损价赋值
            }
        }

        if (zy_percenValue == one_hundred_percent) {
            mEtStopSurplus.setText("");    //止盈价赋值
        } else {
            double zylldistance = (referenceMarginPrice * zy_percenValue) / chooseContract;
            if (tradeDiration == TRADE_DIRECTION_BUY) {
                //  如果是买方向
                double buy_sy = mBuyPrice + zylldistance;
                mEtStopSurplus.setText(buy_sy + "");    //止盈价赋值
            } else if (tradeDiration == TRADE_DIRECTION_SELL) {
                //  如果是卖方向
                double sell_zy = mSellPrice - zylldistance;
                mEtStopSurplus.setText(sell_zy + "");    //止盈价赋值
            }
        }


    }

    /**
     * 通过行情信息计算相应的合理的止损价等信息
     *
     * @param bRealTimeQuotePushes
     */
    public void setRealTimeQuotePushes(List<BRealTimeQuotePush> bRealTimeQuotePushes) {
        this.mBrealTimeQuotePush = bRealTimeQuotePushes;
        if (bRealTimeQuotePushes == null && mGoodList == null) {
            return;
        }
        // 重新拼属于自己的bean
        for (Goods goods : mGoodsList) {
            for (BRealTimeQuotePush timePush : bRealTimeQuotePushes) {
                BProductPriceInfo product_price_info = timePush.product_price_info;
                if ((product_price_info.ss_product_code).equals(goods.getSs_product_code())) {
                    goods.uiPrice = timePush.ui_price + "";

                    if (calculation(goods)) return;
                }
            }
        }
        showViewVisable();
    }


    /**
     * 设置商品spinner设置的位置
     *
     * @param selectIndex
     */
    public void setSpinnerSelect(int selectIndex) {
        this.mSppinerIndex = selectIndex;       // 这个指定了选中的是哪个
    }

    /**
     * 商品选中的数据处理逻辑
     *
     * @param selectedItem
     */
    private void showSelectIndexItem(Goods selectedItem) {
        mGoodsChoose = selectedItem.getSs_product_name();
        mTradeCode = selectedItem.getSs_product_code();
        setPriceInfo(mTradeCode);
        showViewGone();

        clearEdit();
        newAccupidMoney = 0;
        // 设值
        mBtChooseGoods.setText(mGoodsChoose);

        chooseContract = StringUtils.toDouble(selectedItem.getDb_contract_size()); // 合约单位


        newAccupidMoney = 0;
        LogUtils.e("NewOrder", mTradeCode);


        // 放在这里倒是正确的，在onresponse 有问题
        getHistoryCachData();

        calurateGuaranteeMoney();
    }

    /**
     * 隐藏相关视图
     */
    private void showViewGone() {
        DialogUtil.showDialog(getActivity());
        mLlNewOrder.setVisibility(View.GONE);
        mBottom.setVisibility(View.GONE);
    }

    /**
     * 显示相关视图
     */
    private void showViewVisable() {
        DialogUtil.dimissDialog();
        if (mLlNewOrder != null) {
            mLlNewOrder.setVisibility(View.VISIBLE);
        }
        if (mBottom != null) {
            mBottom.setVisibility(View.GONE);
        }
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            Double price = StringUtils.toDouble(s.toString());
            if (price <= 0) {
                return;
            }
            String v_add = StringUtils.double_df.format(price + mOrder_s_spread);
            String v_less = StringUtils.double_df.format(price - mOrder_s_spread);
            if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_buylimit))) {
                String str = "止盈>=" + v_add + "止损<=" + v_less;
                mTip3.setText(str);
                mTvTipTab2Yin.setText("止盈>=" + v_add);
                mTvTipTab2Sun.setText("止损<=" + v_less);
            } else if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_selllimit))) {
                String str = "止盈<=" + v_less + "止损>=" + v_add;
                mTip3.setText(str);
                mTvTipTab2Yin.setText("止盈<=" + v_less);
                mTvTipTab2Sun.setText("止损>=" + v_add);
            } else if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_buystop))) {
                String str = "止盈>=" + v_add + "止损<=" + v_less;
                mTip3.setText(str);
                mTvTipTab2Yin.setText("止盈>=" + v_add);
                mTvTipTab2Sun.setText("止损<=" + v_less);
            } else if (mPendingChoose.equals(getActivity().getResources().getString(R.string.pending_type_sellstop))) {
                String str = "止盈<=" + v_less + "止损>=" + v_add;
                mTip3.setText(str);
                mTvTipTab2Yin.setText("止盈<=" + v_less);
                mTvTipTab2Sun.setText("止损>=" + v_add);
            }
        }
    };


    /**
     * @param ss_product_code
     */
    public void setPriceInfo(String ss_product_code) {
        this.mSocketClient = ((MainActivity) getActivity()).getSocketClient();  // 这个socket是属于MainActivity中东西
        mKLineFragment.setPriceInfo(ss_product_code, mSocketClient);
    }

    /**
     * 转接到kfragmnet
     *
     * @param entrySet
     */
    public void setKlineDataForOne(EntrySet entrySet) {
        if (mKLineFragment != null) {
            mKLineFragment.setEntrySet(entrySet);
        }
    }
}
